const Router = require("@koa/router");
const router = new Router();
const { modelUser } = require("@/models/user");
const { verifyCode } = require("@/msgCode/genCode");
const { sendEmailCode } = require("@/msgCode/sendEmail");
const {Auth} = require("@/token/auth");
const {
  Vercode,
  Emailregistration,
  Uploadpassword,
  Login,
  Modifytheuser
} = require("@/validData/user");
const { genToken } = require("@/token/jwt");
const crypto = require("crypto");
const moment = require("moment");
moment.locale("zh-cn");
// 小程序端：发送验证码
router.post("/vercode", async (ctx) => {
  const { email } = ctx.request.body;
  Vercode(email);
  try {
    const res = await sendEmailCode(email);
    console.log(res);

    if (res.success) {
      ctx.send("SUCCESS", 200, { message: "验证码发送成功" });
    } else {
      ctx.send("ERROR", 422, { message: "验证码发送失败" });
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      msg: error || "验证码发送失败",
      data: {
        success: false,
      },
    };
  }
});

// 小程序端，邮箱验证码登录
router.post("/mobile-registration", async (ctx) => {
  const { email, code } = ctx.request.body;
  Emailregistration(email, code);
  // 验证验证码是否正确
  const isValid = verifyCode(email, code);
  if (!isValid) {
    ctx.send("ERROR", 422, { message: "验证码错误" });
    return
  }

  // 判断用户之前是否已有账号
  const res = await modelUser
    .find({ email }, { email: false, my_tags: false })
    .lean();
  if (res.length > 0) {
    const token = { user_Token: genToken(res[0].uid) };
    ctx.send("SUCCESS", 200, {
      ...res[0],
      ...token,
    });
  } else {
    const nickname = "用户_" + email.split("@")[0].slice(-4);
    await modelUser.create({
      email,
      nickname,
    });
    const userData = await modelUser
      .find({ email }, { email: false, my_tags: false })
      .lean();
    console.log('userData',userData);
    const token = { user_Token: genToken(userData.uid) };
    ctx.send("SUCCESS", 200, {
      ...userData[0],
      ...token,
    });
  }
});

// 设置密码，修改密码
router.post("/upload-password", async (ctx) => {
  const { email, code, password } = ctx.request.body;
  Uploadpassword(email, code, password);
  // 验证验证码是否正确
  const isValid = verifyCode(email, code);

  if (!isValid) {
    ctx.send("ERROR", 422, { message: "验证码错误" });
    return;
  }
  // 判断用户之前是否已有账号
  const res = await modelUser.find({ email }).lean();
  if (res.length > 0) {
    // 创建hash对象
    const hash = crypto.createHash("sha256").update(password);
    // 生成hash值
    const passwordHash = hash.digest("hex");
    // 更新密码
    await modelUser.updateOne({ email }, { password: passwordHash });
    ctx.send("SUCCESS", 200, { message: "密码设置成功" });
  } else {
    ctx.send("ERROR", 422, { message: "用户不存在" });
  }
});

// 小程序端，邮箱和密码登录
router.post('/login',async ctx => {
    const {email,password} = ctx.request.body;
    Login(email,password);
    // 创建哈希对象
    const hash = crypto.createHash("sha256").update(password);
    // 生成哈希值
    const passwordHash = hash.digest("hex");
    // 查询用户
    const res = await modelUser.find({email,password:passwordHash},{email:false,my_tags:false}).lean();
    if(res.length>0){
        const token = {user_Token:genToken(res[0].uid)};
        ctx.send("SUCCESS",200,{
            ...res[0],
            ...token
        })
    }else{
        ctx.send("ERROR",422,{message:"账号或密码错误"})
    }
})

// 编辑个人资料
router.post('/modify-the-user',new Auth().m, async ctx=>{
    const {nickname,avatarUrl,gender,birthday,city,backdrop} = ctx.request.body
    console.log('ctx.auth',ctx.auth);
    console.log(nickname,avatarUrl,gender,birthday,city,backdrop);
    Modifytheuser(nickname,avatarUrl,gender,birthday,city,backdrop);
    // 计算年龄
    const age = moment().diff(moment(birthday,'YYYY-MM-DD'),'years');
    const res = await modelUser.findOneAndUpdate(
        {
            uid:ctx.auth.uid
        },
        {
            nickname,
            avatarUrl,
            gender,
            birthday,
            age,
            city,
            backdrop
        },
        {
            new:true,
            select:"nickname avatarUrl gender birthday age city backdrop"
        }
    )
    console.log(res);
    ctx.send("SUCCESS",200,{
        res
    })
})

module.exports = router.routes();
